﻿/// <reference path="../GeneratedArtifacts/viewModel.js" />
var intCurrentItem = 0;
var intPageSize = 5;
var StudentTable;

// Buttons and Menu Render
myapp.BrowseStudents.Previous_postRender = function (element, contentItem) {
    var PreviousButtonOutside = $(element);
    var PreviousButtonInside = $(element).children();

    PreviousButtonOutside.addClass("gray");
    PreviousButtonInside.addClass("orange");
};
myapp.BrowseStudents.Next_postRender = function (element, contentItem) {
    var NextButtonOutside = $(element);
    var NextButtonInside = $(element).children();

    NextButtonOutside.addClass("gray");
    NextButtonInside.addClass("blue");

};
myapp.BrowseStudents.AddStudent_postRender = function (element, contentItem) {
    var AddStudentButtonOutside = $(element);
    var AddStudentButtonInside = $(element).children();

    AddStudentButtonOutside.addClass("gray");
    AddStudentButtonInside.addClass("green");
};
myapp.BrowseStudents.ButtonMenu_postRender = function (element, contentItem) {
    var MenuElementElementInside = $(element);
    MenuElementElementInside.css({
        "position": "relative",
        "float": "right"
    });
};

// Grid Render
myapp.BrowseStudents.StudentsGrid_render = function (element, contentItem) {
    // clear the element
    element.innerHTML = "";

    // Create a table
    var strTable = "<table id='studentTable' class='ui-responsive table-stroke'";
    strTable = strTable + " data-role='table' data-mode='reflow'></table>";
    StudentTable = $(strTable);

    // Create thead
    var theadTemplate = $("<thead></thead>");
    theadTemplate.appendTo($(StudentTable));

    // Create tableRow
    var tablerowTemplate = $("<tr class='ui-bar-d'></tr>");
    tablerowTemplate.appendTo($(theadTemplate));

    // Crate Columns
    var Column1Template = $("<th data-priority='6'>ID</th>");
    Column1Template.appendTo($(tablerowTemplate));
    var Column2Template = $("<th data-priority='1'>First Name</th>");
    Column2Template.appendTo($(tablerowTemplate));
    var Column3Template = $("<th data-priority='2'>Last Name</th>");
    Column3Template.appendTo($(tablerowTemplate));
    var Column4Template = $("<th data-priority='3'>Birthdate</th>");
    Column4Template.appendTo($(tablerowTemplate));
    var Column5Template = $("<th data-priority='4'>Grade Level</th>");
    Column5Template.appendTo($(tablerowTemplate));
    var Column6Template = $("<th data-priority='5'>Gender</th>");
    Column6Template.appendTo($(tablerowTemplate));

    // Create tableBody
    var tablebodyTemplate = $("<tbody></tbody>");
    tablebodyTemplate.appendTo($(StudentTable));

    // Complete the element    
    StudentTable.appendTo($(element));

    // Function to show items  
    // This is required because the removeEventListener 
    // requires the same instance of the handler to be able to remove it 
    // see: http://social.msdn.microsoft.com/Forums/en-US/lightswitch/thread/d509bee9-99f9-446d-ab22-812b7f73e683/
    function onVisualCollectionLoaded() {
        // Show the data in the JQuery reflow table
        showItems(intCurrentItem, intPageSize, contentItem.screen);
    }

    // Show Data
    // From: http://blogs.msdn.com/b/lightswitch/archive/2013/01/14/visualizing-list-data-using-a-map-control-heinrich-wendel.aspx
    var visualCollection = contentItem.value;
    // Do we have data?
    if (visualCollection.isLoaded) {
        // Load the data
        onVisualCollectionLoaded();
    } else {
        // Create a addChangeListener that will fire when the data is loaded
        visualCollection.addChangeListener("isLoaded", onVisualCollectionLoaded);
        // Load the data
        visualCollection.load();
    }

    // Clean up addChangeListener when screen is closed.
    contentItem.handleViewDispose(function () {
        // Remove the isLoaded change listener
        visualCollection.removeChangeListener(
            "isLoaded", onPropertyChanged);
    });
};

// Button Actions

myapp.BrowseStudents.Previous_Tap_execute = function (screen) {
    // Only move back if we are not on the first record
    if (intCurrentItem > 0) {
        // Move the current record back by the page size
        intCurrentItem = intCurrentItem - intPageSize;
        showItems(intCurrentItem, intCurrentItem + intPageSize, screen);
    }
};

myapp.BrowseStudents.Next_Tap_execute = function (screen) {
    // We always try to move forward at this point
    // We may move back (later in this method) 
    // If we are moving too far forward
    intCurrentItem = intCurrentItem + intPageSize;

    // If we are trying to move to a record 
    // that is higher than all the records we have
    // try to load more records
    if (intCurrentItem + intPageSize >= screen.Students.count) {
        // See if we can load more records
        if (screen.Students.canLoadMore) {
            // We can load more records -- load them
            screen.Students.loadMore().then(function (result) {
                showItems(intCurrentItem, intCurrentItem + intPageSize, screen);
            });
        } else {
            // If we are here then we have no more records to load
            // See if we have moved too far forward
            if (intCurrentItem >= screen.Students.count) {
                //We have moved too far forward so move back
                intCurrentItem = intCurrentItem - intPageSize;
            }
            showItems(intCurrentItem, intCurrentItem + intPageSize, screen);
        }
    } else {
        // We are trying to show records that we already have loaded 
        // Show them 
        showItems(intCurrentItem, intCurrentItem + intPageSize, screen);
    }
};

// Utility

function showItems(start, end, screen) {
    // Remove existing rows
    StudentTable.find("tr:gt(0)").remove();

    $.each(screen.Students.data, function (i, student) {
        if (i >= start && i < end) {
            // Create tableRow
            var tablecontentrowTemplate = $("<tr></tr>");
            tablecontentrowTemplate.appendTo($(StudentTable));

            // Set the row iD
            tablecontentrowTemplate.id = student.Id;

            // Create ID
            var IdTemplate = $("<th>" + student.Id + "</th>");
            IdTemplate.appendTo($(tablecontentrowTemplate));

            // Create FirstName
            var FirstNameTemplate = $("<td>").text(student.FirstName);
            FirstNameTemplate.appendTo($(tablecontentrowTemplate));

            // Create LastName
            var LastNameTemplate = $("<td>").text(student.LastName);
            LastNameTemplate.appendTo($(tablecontentrowTemplate));

            // Create Birthdate
            var dtBirthdate = new Date(student.Birthdate);
            var formattedBirthDate =
                ((dtBirthdate.getMonth() + 1) + "/" + dtBirthdate.getDate() + "/" + dtBirthdate.getFullYear());
            var BirthdateTemplate = $("<td>" + formattedBirthDate + "</td>");
            BirthdateTemplate.appendTo($(tablecontentrowTemplate));

            // Create GradeLevel
            var GradeLevelTemplate = $("<td>" + student.GradeLevel + "</td>");
            GradeLevelTemplate.appendTo($(tablecontentrowTemplate));

            // Create Gender
            var GenderTemplate = $("<td>").text(student.Gender);
            GenderTemplate.appendTo($(tablecontentrowTemplate));

            // Change mouse curser to hand 
            $(tablecontentrowTemplate).css('cursor', 'pointer');

            // Add click event
            $(tablecontentrowTemplate).click(function () {
                // Id of selected Student
                var selectedStudentID = tablecontentrowTemplate.id;
                // Get the selected Student
                myapp.activeDataWorkspace.ApplicationData.Students_SingleOrDefault(selectedStudentID)
                    .execute()
                    .then(function (result) {
                    // Set the selected Student
                    screen.Students.selectedItem = result.results[0];
                    // Show selected Student in Edit screen
                    myapp.showAddEditStudent(screen.Students.selectedItem,{
                        afterClosed: function (addEditScreen, navigationAction) {
                            // If the user commits a change,
                            // show the new Student in Browse Screen.
                            if (navigationAction === msls.NavigateBackAction.commit) {
                                // Update the Grid//
                                showItems(intCurrentItem, intCurrentItem + intPageSize, screen);
                            }
                        }
                    });
                });
            });
        };
    });

    // Refresh the StudentTable
    StudentTable.table("refresh");
};
myapp.BrowseStudents.AddStudent_Tap_execute = function (screen) {
    myapp.showAddEditStudent(null, {
        beforeShown: function (addEditScreen) {
            // Create new Student here so that
            // discard will work.
            var newStudent = new myapp.Student();
            addEditScreen.Student = newStudent;
        },
        afterClosed: function (addEditScreen, navigationAction) {
            // If the user commits the change,
            // show the new Student in Browse Screen.
            if (navigationAction === msls.NavigateBackAction.commit) {
                // Update the Grid//
                showItems(intCurrentItem, intCurrentItem + intPageSize, screen);
            }
        }
    });
};